// 游戏配置
const config = {
    canvasWidth: 400,
    canvasHeight: 400,
    gridSize: 20,
    initialSpeed: 150,
    speedIncrease: 5
};

// 游戏状态
let gameState = {
    snake: [],
    food: {},
    direction: 'right',
    score: 0,
    highScore: 0,
    gameRunning: false,
    gameLoop: null,
    currentSpeed: config.initialSpeed
};

// DOM 元素
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const currentScoreEl = document.getElementById('current-score');
const highScoreEl = document.getElementById('high-score');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
const gameOverModal = document.getElementById('game-over-modal');
const finalScoreEl = document.getElementById('final-score');
const playAgainBtn = document.getElementById('play-again-btn');

// 初始化游戏
function initGame() {
    // 从本地存储加载最高分
    const savedHighScore = localStorage.getItem('snakeHighScore');
    if (savedHighScore) {
        gameState.highScore = parseInt(savedHighScore);
        highScoreEl.textContent = gameState.highScore;
    }

    // 设置画布大小
    canvas.width = config.canvasWidth;
    canvas.height = config.canvasHeight;

    // 绑定事件监听器
    startBtn.addEventListener('click', startGame);
    restartBtn.addEventListener('click', restartGame);
    playAgainBtn.addEventListener('click', restartGame);
    document.addEventListener('keydown', handleKeyPress);

    // 绘制初始界面
    drawInitialScreen();
}

// 绘制初始界面
function drawInitialScreen() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#667eea';
    ctx.font = '20px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('点击"开始游戏"开始', canvas.width / 2, canvas.height / 2);
}

// 开始游戏
function startGame() {
    if (gameState.gameRunning) return;

    // 重置游戏状态
    gameState.snake = [
        { x: 5, y: 5 },
        { x: 4, y: 5 },
        { x: 3, y: 5 }
    ];
    gameState.direction = 'right';
    gameState.score = 0;
    gameState.gameRunning = true;
    gameState.currentSpeed = config.initialSpeed;

    // 生成第一个食物
    generateFood();

    // 更新UI
    currentScoreEl.textContent = gameState.score;
    startBtn.style.display = 'none';
    restartBtn.style.display = 'inline-block';

    // 开始游戏循环
    gameState.gameLoop = setInterval(gameStep, gameState.currentSpeed);
}

// 游戏主循环
function gameStep() {
    moveSnake();
    if (checkCollision()) {
        endGame();
        return;
    }
    
    if (checkFoodCollision()) {
        eatFood();
    }
    
    draw();
}

// 移动蛇
function moveSnake() {
    const head = { ...gameState.snake[0] };
    
    switch (gameState.direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    gameState.snake.unshift(head);
    
    // 如果没有吃到食物，移除尾部
    if (!checkFoodCollision()) {
        gameState.snake.pop();
    }
}

// 检查碰撞
function checkCollision() {
    const head = gameState.snake[0];
    
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= config.canvasWidth / config.gridSize ||
        head.y < 0 || head.y >= config.canvasHeight / config.gridSize) {
        return true;
    }
    
    // 检查自身碰撞
    for (let i = 1; i < gameState.snake.length; i++) {
        if (head.x === gameState.snake[i].x && head.y === gameState.snake[i].y) {
            return true;
        }
    }
    
    return false;
}

// 检查食物碰撞
function checkFoodCollision() {
    const head = gameState.snake[0];
    return head.x === gameState.food.x && head.y === gameState.food.y;
}

// 吃食物
function eatFood() {
    gameState.score += 1;
    currentScoreEl.textContent = gameState.score;
    
    // 更新最高分
    if (gameState.score > gameState.highScore) {
        gameState.highScore = gameState.score;
        highScoreEl.textContent = gameState.highScore;
        localStorage.setItem('snakeHighScore', gameState.highScore);
    }
    
    // 生成新食物
    generateFood();
    
    // 增加速度
    if (gameState.currentSpeed > 50) {
        gameState.currentSpeed -= config.speedIncrease;
        clearInterval(gameState.gameLoop);
        gameState.gameLoop = setInterval(gameStep, gameState.currentSpeed);
    }
}

// 生成食物
function generateFood() {
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.random() * (config.canvasWidth / config.gridSize)),
            y: Math.floor(Math.random() * (config.canvasHeight / config.gridSize))
        };
    } while (gameState.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    
    gameState.food = newFood;
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制背景
    ctx.fillStyle = '#f9f9f9';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格
    ctx.strokeStyle = '#e0e0e0';
    ctx.lineWidth = 1;
    for (let i = 0; i <= config.canvasWidth; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, config.canvasHeight);
        ctx.stroke();
    }
    for (let i = 0; i <= config.canvasHeight; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(config.canvasWidth, i);
        ctx.stroke();
    }
    
    // 绘制蛇
    gameState.snake.forEach((segment, index) => {
        if (index === 0) {
            // 蛇头
            ctx.fillStyle = '#667eea';
        } else {
            // 蛇身
            ctx.fillStyle = '#764ba2';
        }
        ctx.fillRect(
            segment.x * config.gridSize + 1,
            segment.y * config.gridSize + 1,
            config.gridSize - 2,
            config.gridSize - 2
        );
    });
    
    // 绘制食物
    ctx.fillStyle = '#ff6b6b';
    ctx.beginPath();
    const foodX = gameState.food.x * config.gridSize + config.gridSize / 2;
    const foodY = gameState.food.y * config.gridSize + config.gridSize / 2;
    ctx.arc(foodX, foodY, config.gridSize / 2 - 2, 0, 2 * Math.PI);
    ctx.fill();
}

// 处理键盘输入
function handleKeyPress(event) {
    if (!gameState.gameRunning) return;
    
    const key = event.key;
    const currentDirection = gameState.direction;
    
    switch (key) {
        case 'ArrowUp':
            if (currentDirection !== 'down') gameState.direction = 'up';
            break;
        case 'ArrowDown':
            if (currentDirection !== 'up') gameState.direction = 'down';
            break;
        case 'ArrowLeft':
            if (currentDirection !== 'right') gameState.direction = 'left';
            break;
        case 'ArrowRight':
            if (currentDirection !== 'left') gameState.direction = 'right';
            break;
    }
    
    // 防止方向键滚动页面
    if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(key)) {
        event.preventDefault();
    }
}

// 结束游戏
function endGame() {
    gameState.gameRunning = false;
    clearInterval(gameState.gameLoop);
    
    // 显示游戏结束模态框
    finalScoreEl.textContent = gameState.score;
    gameOverModal.style.display = 'flex';
}

// 重新开始游戏
function restartGame() {
    gameOverModal.style.display = 'none';
    startGame();
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);